<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\model\qa\Answers;
use app\common\model\qa\Question;
use app\common\validate\QaValidate;
use think\Db;

/**
 * 问答控制器
 */
class Qa extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    //添加问答
    public function add() {
        (new QaValidate())->goCheck('add');
        $data = [
            'name' => input('name', ''),
            'user_id' => UID,
            'org_cate_id' => ORG_CATE_ID
        ];
        $q = new Question($data);
        $res = $q->allowField(true)->isUpdate(false)->save();
        if (!$res) {
            $this->error('发问失败');
        } else {
            $this->success('提问成功');
        }
    }

    public function getList() {
        $where['org_cate_id'] = ORG_CATE_ID;
        $my = input('my', 0);//1代表我的问答
        if ($my == 1) {
            $where['user_id'] = UID;
        }
        $q = new Question();
        $list = $q->where($where)->order('createtime desc')->paginate()->each(function($item, $key) {
            $item->append(['count_text', 'new_info']);
        });

        $this->success('问题列表', $list->toArray());
    }

    //回答列表
    public function getAnswer () {
        $id = input('id/d', 0);
        //第一页返回问题信息 ， 其他页面 不反回
        $page = input('page/d', 1);
        $q_info = [];
        if ($page === 1) {
            $q = new Question();
            $q_info = $q->where(['id'=> $id])->find()->append(['count_text']);
            $user = Db::name('user')->where('id', $q_info['user_id'])->find();
            $q_info['image'] = $user['avatar'];
            $q_info['nickname'] = $user['nickname'];
        }

        //获取答案列表
        $a = new Answers();
        $where['parent_questions_id'] = $id;
        $list = $a->where($where)->order('createtime desc')->paginate()->each(function($item, $key) {
            $item->append(['user_info']);
        });

        $this->success('回答列表', [
            'list' => $list,
            'q_info' => $q_info
        ]);
    }

    //提交问题答案
    public function addAnswer() {
        (new QaValidate())->goCheck('answer');
        $data = [
            'anster' => input('anster', ''),
            'user_id' => UID,
            'org_cate_id' => ORG_CATE_ID,
            'parent_questions_id' => input('parent_questions_id/d', 0)
        ];
        $a = new Answers($data);
        $res = $a->allowField(true)->isUpdate(false)->save();
        if (!$res) {
            $this->error('回答失败');
        } else {
            $this->success('提交成功');
        }
    }
}
